"""
安装脚本
自动安装依赖并配置环境
"""

import os
import sys
import subprocess
from pathlib import Path

def print_banner():
    """打印欢迎横幅"""
    print("=" * 60)
    print("🤖 AI合同审核系统 - 安装程序")
    print("=" * 60)
    print()

def check_python_version():
    """检查Python版本"""
    print("🔍 检查Python版本...")
    
    if sys.version_info < (3, 8):
        print("❌ 错误: 需要Python 3.8或更高版本")
        print(f"   当前版本: {sys.version}")
        return False
    
    print(f"✅ Python版本检查通过: {sys.version}")
    return True

def install_dependencies():
    """安装依赖包"""
    print("\n📦 安装依赖包...")
    
    try:
        # 升级pip
        print("   升级pip...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
        
        # 安装requirements.txt中的依赖
        requirements_file = Path(__file__).parent / "requirements.txt"
        if requirements_file.exists():
            print("   安装项目依赖...")
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", "-r", str(requirements_file)
            ])
        else:
            print("❌ 未找到requirements.txt文件")
            return False
        
        print("✅ 依赖包安装完成")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖包安装失败: {e}")
        return False

def setup_directories():
    """创建必要的目录"""
    print("\n📁 创建项目目录...")
    
    project_root = Path(__file__).parent
    directories = [
        "uploads",
        "reports", 
        "templates",
        "static",
        "logs",
        "backups"
    ]
    
    for dir_name in directories:
        dir_path = project_root / dir_name
        dir_path.mkdir(exist_ok=True)
        print(f"   ✅ {dir_name}/")
    
    print("✅ 目录创建完成")

def setup_environment():
    """设置环境配置"""
    print("\n⚙️ 配置环境...")
    
    project_root = Path(__file__).parent
    env_example = project_root / ".env.example"
    env_file = project_root / ".env"
    
    if env_example.exists() and not env_file.exists():
        # 复制示例配置文件
        with open(env_example, 'r', encoding='utf-8') as f:
            content = f.read()
        
        with open(env_file, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print("   ✅ 已创建.env配置文件")
        print("   💡 请编辑.env文件并填入您的API密钥")
    else:
        print("   ℹ️ 环境配置文件已存在")

def test_installation():
    """测试安装"""
    print("\n🧪 测试安装...")
    
    try:
        # 测试导入主要模块
        import streamlit
        import openai
        print("   ✅ 核心模块导入成功")
        
        # 测试项目模块
        sys.path.append(str(Path(__file__).parent))
        from config import Config
        from services.document_processor import DocumentProcessor
        print("   ✅ 项目模块导入成功")
        
        return True
        
    except ImportError as e:
        print(f"   ❌ 模块导入失败: {e}")
        return False

def print_next_steps():
    """打印后续步骤"""
    print("\n🎉 安装完成!")
    print("\n📋 后续步骤:")
    print("1. 编辑 .env 文件，填入您的OpenAI API密钥")
    print("2. 运行 'python run.py' 启动系统")
    print("3. 在浏览器中访问 http://localhost:8501")
    print("\n📚 更多信息请查看 README.md 文件")
    print("\n" + "=" * 60)

def main():
    """主安装流程"""
    print_banner()
    
    # 检查Python版本
    if not check_python_version():
        sys.exit(1)
    
    # 安装依赖
    if not install_dependencies():
        print("\n❌ 安装失败，请检查错误信息")
        sys.exit(1)
    
    # 设置目录
    setup_directories()
    
    # 设置环境
    setup_environment()
    
    # 测试安装
    if not test_installation():
        print("\n⚠️ 安装可能存在问题，请检查依赖")
    
    # 打印后续步骤
    print_next_steps()

if __name__ == "__main__":
    main()
